<?php
/**
 * 文章内容分页插件
 * 说明：本分页只针对UEditor编辑器上传的分页内容，分页分隔符为_ueditor_page_break_tag_
 * 本插件为ThinkCMF5专用
 * Author: 灰大狼
 * Email: crazys@126.com
 */

namespace plugins\crazy_content_page;

use cmf\lib\Plugin;
use cmf\paginator\Bootstrap;

class CrazyContentPagePlugin extends Plugin
{
    public $info = [
        'name'        => 'CrazyContentPage',
        'title'       => '文章内容分页插件',
        'description' => '对于内容过长的文章，编辑时添加分页了标识后，则可以分页显示。',
        'status'      => 1,
        'author'      => '惠达浪',
        'version'     => '1.0.2',
        'demo_url'    => 'https://www.crazys.pub',
        'author_url'  => 'https://www.qdcrazy.cc'
    ];

    public $hasAdmin = 0;

    /**
     * 插件安装
     * @return bool
     */
    public function install()
    {
        return true;
    }

    /**
     * 插件卸载
     * @return bool
     */
    public function uninstall()
    {
        return true;
    }


    /**
     * 实现portal_before_assign_article钩子方法
     * @param array $article 需要处理的文章
     */
    public function portalBeforeAssignArticle($article)
    {
        if (empty($article['post_content'])) {
            return;
        }

        $contents  = explode('_ueditor_page_break_tag_', $article['post_content']);
        $totalPage = count($contents);

        $article['page'] = '';
        if ($totalPage > 1) {
            $config                  = $this->getConfig();
            $request                 = request();
            $currentPage             = $request->param('page', 1, 'intval');
            $options                 = ['prev' => $config['prev'] ?: '<', 'next' => $config['next'] ?: '>', 'path' => $request->baseUrl()];
            $Page                    = new Bootstrap($contents, 1, $currentPage, $totalPage, null, $options);
            $article['post_content'] = $contents[$currentPage - 1];
            $article['page']         = $Page->render();
        }
    }
}